/* eslint-disable */
import axios from 'axios'
import {
    Message,
    MessageBox,
    Loading
} from 'element-ui'
import store from '../utils/factory'
import router from '../router'

// 创建axios实例
const service = axios.create({
    timeout: 10000, // 请求超时时间
    responseType: 'json'
});

// request拦截器
service.interceptors.request.use(config => {
    // config.headers['Authorization'] = store.get("access_token") || "";
    // if (config.headers['haveBear']) {
    //     config.headers['Authorization'] = 'Bear ' + store.get("access_token")
    // }
    config.headers['Authorization'] = 'Bearer ' + store.get("access_token") || ""
    return config
}, error => {
    Promise.reject(error)
});

// respone拦截器
service.interceptors.response.use(
    response => {
        if (!response) {
            return Promise.reject("error")
        }
        if (response.request.responseType == "blob") {
            return response
        }
        const res = response.data
        if (res.code != 0) {
            Message({
                message: res.msg,
                type: 'error',
                duration: 5 * 1000
            });
            return Promise.reject("error")
        }
        return res
    },
    error => {
        if (!error.response) {
            Message({
                message: "网络异常或服务器报错",
                type: 'error',
                duration: 5 * 1000
            });
            return false
        }
        if (error.response.status == "401") {
            MessageBox.confirm('登录失效，请重新登录', '确定登出', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                router.push("/")
            })
        } else {
            Message({
                message: error.message,
                type: 'error',
                duration: 5 * 1000
            });
        }
        return Promise.reject(error)
    }
);

export default service